/**
 * @Author YuanYuan
 * @Date 2022/8/14
 * @Time 10:11
 */

import java.util.Random;

/**
 * 给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
 * 实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
 * 其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
 * 最终再汇总两个和, 进行相加
 * 记录程序的执行时间.
 * @return
*/

public class SumFun {
    public static final int COUNT = 1000_0000;

    public int[] arr = new int[COUNT];
    long singleSum = 0;
    long doubleSum = 0;

    public void sum() throws InterruptedException{

        Long start = System.currentTimeMillis();
        Random random = new Random();
        for (int i = 0; i < arr.length; i++) {
            arr[i] = random.nextInt(100) + 1;
        }




        Thread thread = new Thread(()-> {
            for (int i = 1; i < arr.length; i+=2) {
                singleSum += arr[i];
            }
        });

//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                for (int i = 0; i < arr.length; i+=2) {
//                    doubleSum += arr[i];
//                }
//            }
//        };

        Thread thread1 = new Thread(()-> {
            for (int i = 0; i < arr.length; i+=2) {
                    doubleSum += arr[i];
                }
        });
        //runnable.run();
        thread.start();
        thread1.start();

        //runnable.wait();
        thread1.join();
        thread.join();

        long end = System.currentTimeMillis();
        System.out.println(singleSum + doubleSum);
        System.out.println("执行时间为:" + (end - start) + "ms");

    }
}
